﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;

namespace FaWorks.WebSocket.Service
{
    public class MessageService
        : IMessageService
    {
        IMessageCallback _callback = null;

        public MessageService()
        {
            _callback = MessageManager.CreateMessageCallback(OperationContext.Current);
        }

        public void Receive(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            WebSocketMessageProperty property =
                    message.Properties[WebSocketMessageProperty.Name] as WebSocketMessageProperty;
            
            WebSocketContext context = property.WebSocketContext;
            var queryParameters = HttpUtility.ParseQueryString(context.RequestUri.Query);
            string content = string.Empty;

            if (!message.IsEmpty)
            {
                byte[] body = message.GetBody<byte[]>();
                content = Encoding.UTF8.GetString(body);
            }

            // Do something with the content/queryParams
            // ...
            
            string str = null;
            if (string.IsNullOrEmpty(content)) // Connection open message
            {
                str = "Opening connection from user " +
                        queryParameters["Name"].ToString();
            }
            else // Message received from client
            {
                str = "Received message: " + content;
            }

            MessageManager.Brocast(str);
        }

        
    }
}
